package servlet;

import service.UserService;
import model.User;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@WebServlet("/profile")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
    maxFileSize = 1024 * 1024 * 10,      // 10MB
    maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class ProfileServlet extends HttpServlet {
    private UserService userService = new UserService();
    
    // 头像存储目录
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 添加字符编码设置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 检查用户登录状态
        User currentUser = SessionUtils.getCurrentUser(request);
        if (currentUser == null) {
            response.sendRedirect("login.html");
            return;
        }

        // 获取当前用户信息
        User user = userService.findById(currentUser.getId());
        request.setAttribute("user", user);
        // 修改 doGet 方法中的转发路径
        request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 添加字符编码设置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 检查用户登录状态
        User currentUser = SessionUtils.getCurrentUser(request);
        if (currentUser == null) {
            response.sendRedirect("login.html");
            return;
        }

        // 获取表单数据
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String avatar = null;
    
        // 验证输入
        if (username == null || username.trim().isEmpty() || email == null || email.trim().isEmpty()) {
            User user = userService.findById(currentUser.getId());
            request.setAttribute("user", user);
            request.setAttribute("error", "昵称和邮箱不能为空");
            // 修改转发路径
            request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
            return;
        }
    
        // 处理文件上传
        try {
            Part filePart = request.getPart("avatar");
            if (filePart != null && filePart.getSize() > 0) {
                // 获取文件名
                String fileName = extractFileName(filePart);
                
                // 检查文件类型
                if (!isImageFile(fileName)) {
                    User user = userService.findById(currentUser.getId());
                    request.setAttribute("user", user);
                    request.setAttribute("error", "请上传有效的图片文件");
                    // 修改转发路径
                    request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
                    return;
                }
                
                // 生成唯一文件名
                String uniqueFileName = generateUniqueFileName(fileName);
                
                // 获取上传目录的绝对路径
                String applicationPath = request.getServletContext().getRealPath("/");
                String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
                
                // 创建上传目录（如果不存在）
                File uploadDir = new File(uploadFilePath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                
                // 保存文件
                String filePath = uploadFilePath + File.separator + uniqueFileName;
                filePart.write(filePath);
                
                // 设置头像URL
                avatar = "/" + UPLOAD_DIR + "/" + uniqueFileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "文件上传失败");
            User user = userService.findById(currentUser.getId());
            request.setAttribute("user", user);
            // 修改转发路径
            request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
            return;
        }
    
        // 更新用户资料
        boolean success = userService.updateProfile(currentUser.getId(), username, email, avatar);
        
        // 重新获取更新后的用户信息
        User updatedUser = userService.findById(currentUser.getId());
        
        if (success) {
            // 更新session中的用户信息
            SessionUtils.setCurrentUser(request, updatedUser);
            request.setAttribute("user", updatedUser);
            request.setAttribute("success", "个人资料更新成功");
        } else {
            request.setAttribute("user", updatedUser);
            request.setAttribute("error", "个人资料更新失败，请检查邮箱是否已被使用");
        }
        
        // 修改转发路径
        request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
    }
    
    // 从Part对象中提取文件名
    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split("; ");
        for (String s : items) {
            if (s.startsWith("filename=")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
    
    // 检查是否为图片文件
    private boolean isImageFile(String fileName) {
        String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif"};
        for (String ext : allowedExtensions) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
    
    // 生成唯一文件名
    private String generateUniqueFileName(String originalFileName) {
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String randomId = UUID.randomUUID().toString().substring(0, 8);
        String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        return "avatar_" + timestamp + "_" + randomId + extension;
    }
}